<template>
  <div class="pagination">
    <button :disabled="pageNo === 1" @click="$emit('getpaggoods', pageNo - 1)">
      上一页
    </button>
    <button v-if="startEnd.start > 1" @click="$emit('getpaggoods', 1)">
      1
    </button>
    <button v-if="startEnd.start > 2">···</button>
    <!-- 中间的button 需要遍历出来 -->
    <!-- 加active的类名  假如当前页数为1 就会在1 2 3 4 5中去遍历 
    如果当前页正好等于其中的一页 就高亮显示
    -->
    <button
      v-for="num in startEnd.end - startEnd.start + 1"
      :key="num"
      :class="{ active: pageNo === num + startEnd.start - 1 }"
      @click="$emit('getpaggoods', num + startEnd.start - 1)"
    >
      {{ num + startEnd.start - 1 }}
    </button>
    <button v-if="startEnd.end < totalPage - 1">···</button>
    <button
      v-if="startEnd.end < totalPage"
      @click="$emit('getpaggoods', totalPage)"
    >
      {{ totalPage }}
    </button>
    <button
      :disabled="pageNo === totalPage"
      @click="$emit('getpaggoods', pageNo + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>
<!--  -->
<script>
export default {
  name: 'Pagination',
  props: {
    total: Number,
    pageNo: {
      type: Number,
      default: 1,
    },
    continues: {
      type: Number,
      required: true,
    },
    pageSize: {
      type: Number,
      default: 5,
    },
  },
  computed: {
    // 计算当前的总页数
    totalPage() {
      return Math.ceil(this.total / this.pageSize)
    },
    // 计算当前页的起始页和结束页
    startEnd() {
      let start = 0
      let end = 0
      let { totalPage, continues, pageNo } = this
      if (continues > totalPage) {
        start = 1
        end = totalPage
      } else {
        // 正常情况下
        start = pageNo - Math.floor(continues / 2)
        end = pageNo + Math.floor(continues / 2)
        if (start < 1) {
          start = 1
          end = continues
        }

        if (end > totalPage) {
          start = totalPage - continues + 1
          end = totalPage
        }
      }
      return {
        start,
        end,
      }
    },
  },
}
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
